package com.cjm.algorithm.leetcode;

import com.cjm.algorithm.TreeNode;
import com.sun.jmx.remote.internal.ArrayQueue;

import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @see <a href=https://leetcode-cn.com/problems/binary-tree-level-order-traversal/>二叉树的层序遍历</a>
 */
public class LevelOrder102 {
    public List<List<Integer>> levelOrderone(TreeNode root) {
        List<List<Integer>> res =new ArrayList<>();
        if (root == null) return res;

        LinkedList<TreeNode> linkedList = new LinkedList();
        linkedList.add(root);
        while (!linkedList.isEmpty()) {
            int size = linkedList.size();
            List<Integer> xx = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode treeNode = linkedList.pollFirst();
                xx.add(treeNode.val);

                if (treeNode.left != null) linkedList.addLast(treeNode.left);
                if (treeNode.right != null) linkedList.addLast(treeNode.right);
            }
            res.add(xx);
        }
        return res;
    }
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }

        List<List<Integer>> res = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedBlockingQueue();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> temp = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if (poll == null) {
                    break;
                }
                temp.add(poll.val);
                if (poll.left != null) {
                    queue.add(poll.left);
                }
                if (poll.right != null) {
                    queue.add(poll.right);
                }
            }
            res.add(temp);
        }
        return res;
    }

    public static void main(String[] args) {
    }
}
